using System;
using System.Collections.Generic;
using System.Text;
using Universe.Farm.Service.Mesages;

namespace Universe.Farm.Service
{
    class AcquireStation
    {
        public static bool Aquiare(FarmState state, AnnounceMessage message)
        {
            lock(state.HealthState)
            {
                Dictionary<string, HealthStamped> byComputer;
                if (!state.HealthState.TryGetValue(message.Computer, out byComputer))
                {
                    byComputer = new Dictionary<string, HealthStamped>();
                    state.HealthState[message.Computer] = byComputer;
                }

                HealthStamped healthStamped;
                if (!byComputer.TryGetValue(message.IdService, out healthStamped ))
                {
                    healthStamped = null;
                }

                HealthInfo newInfo = new HealthInfo(
                    message.Computer,
                    message.IdService,
                    message.IsOK,
                    message.Description
                    );

                if (healthStamped == null)
                {

                    healthStamped = new HealthStamped(message.Stamp, newInfo);

                    byComputer[message.IdService] = healthStamped;
                    return true;
                }

                else
                {
                    if (healthStamped.Stamp.CompareTo(message.Stamp) < 0)
                    {
                        byComputer[message.IdService] = 
                            new HealthStamped(message.Stamp, newInfo);

                        return true;
                    }

                    return false;
                }
            }
        }

        public static bool Acquire(FarmState state, ByeMessage message)
        {
            lock (state.HealthState)
            {
                Dictionary<string, HealthStamped> byComputer;
                if (state.HealthState.TryGetValue(message.Computer, out byComputer))
                {
                    state.HealthState.Remove(message.Computer);
                    return true;
                }
            }

            return false;
        }
        
        public static bool IsNew(FarmState state, MessageHeader messageHeader)
        {
            TimeStamp storedStamp;
            bool ret;
            if (!state.Stamps.TryGetValue(messageHeader.ComputerID, out storedStamp))
            {
                ret = true;
                state.Stamps[messageHeader.ComputerID] = messageHeader.Stamp;
            }
            else
            {
                ret = storedStamp.CompareTo(messageHeader.Stamp) < 0;
                if (ret)
                {
                    state.Stamps[messageHeader.ComputerID] = messageHeader.Stamp;
                }
            }

            return ret;
        }
        
    }
}
